<template>
    <div class="report-management">
        <!-- 搜索区域 -->
        <div class="search-area">
            <el-form :inline="true" :model="searchForm">
                <el-form-item label="报表名称">
                    <el-input size="small" v-model="searchForm.filename" placeholder="请输入报表名称" />
                </el-form-item>
                <el-form-item>
                    <el-button size="small" type="primary" @click="handleSearch">查询</el-button>
                </el-form-item>
                <el-form-item>
                    <el-button size="small" type="primary" @click="handleAdd">新增</el-button>
                </el-form-item>
            </el-form>
        </div>

        <!-- 报表列表 -->
        <div class="table-area">
            <el-table :data="reportList" style="width: 100%">
                <el-table-column prop="id" label="序号" width="80" align="center">
                    <template slot-scope="scope">
                        {{ scope.$index + 1 }}
                    </template>
                </el-table-column>

                <el-table-column prop="filename" label="报表名称" />
                <el-table-column prop="filetype" label="类型">
                    <template slot-scope="scope">
                        {{dict.type["sys_report_type"] && dict.type["sys_report_type"].find(item => item.value == scope.row.filetype) ? dict.type["sys_report_type"].find(item => item.value == scope.row.filetype).label : '-'}}
                        <!-- {{ dict.type["sys_report_type"].find(item => item.value == scope.row.filetype).label }} -->
                    </template>
                </el-table-column>
                <el-table-column prop="cteateby" label="人员" />
                <el-table-column prop="filetime" label="时间">
                    <template slot-scope="scope">
                        {{ scope.row.filetime | formatDate }}
                    </template>
                </el-table-column>
                <el-table-column prop="checkstate" label="状态">
                    <!-- 0-待审核 1-通过 2-驳回 -->
                    <template slot-scope="scope">
                        <el-tag v-if="scope.row.checkstate == 0" type="info">待审核</el-tag>
                        <el-tag v-if="scope.row.checkstate == 1" type="success">通过</el-tag>
                        <el-tag v-if="scope.row.checkstate == 2" type="danger">驳回</el-tag>
                    </template>
                </el-table-column>
                <el-table-column label="操作" width="150" fixed="right">
                    <template slot-scope="scope">
                        <el-button type="text" @click="handleEdit(scope.row)">修改</el-button>
                        <el-button type="text" @click="handleAudit(scope.row)">审核</el-button>
                    </template>
                </el-table-column>
            </el-table>
        </div>

        <!-- 新增/修改报表弹窗 -->
        <el-dialog title="新增报表" :visible.sync="addDialogVisible" width="500px">
            <el-form :model="addForm" label-width="100px">
                <el-form-item label="报表名称">
                    <el-input v-model="addForm.filename" placeholder="请输入报表名称" />
                </el-form-item>
                <el-form-item label="报表类型">
                    <el-select v-model="addForm.filetype" placeholder="请选择报表类型">
                        <el-option v-for="(item, key) in (dict.type['sys_report_type'] || [])" :key="key" :label="(item && item.label) || ''"
                            :value="(item && item.value) || ''" />
                        <!-- <el-option v-for="(item, key) in dict.type['sys_report_type']" :key="key" :label="item.label" :value="item.value" /> -->
                    </el-select>
                </el-form-item>
                <el-form-item label="发布日期">
                    <el-date-picker v-model="addForm.filetime" type="date" placeholder="选择日期" style="width: 100%" />
                </el-form-item>
                <el-form-item label="附件">
                    <div v-if="addForm.filepath">
                        <el-tag type="success" style="margin-right: 10px;">{{ addForm.filepath }}</el-tag>
                        <el-button size="small" @click="removeFile">删除</el-button>
                    </div>
                    <!-- <el-upload v-else class="upload-demo" action="#" :on-preview="handlePreview" :on-remove="handleRemove"
                        :file-list="fileList" :auto-upload="false" :limit="1" :on-exceed="handleExceed" :on-change="handleFileChange">
                        <el-button slot="trigger" size="small" type="primary">选取文件</el-button>
                    </el-upload> -->
                    <el-upload v-else class="upload-demo" :action="uploadImgUrl" :on-preview="handlePreview"
                        :on-remove="handleRemove" :file-list="fileList" :auto-upload="true" :limit="1"
                        :on-exceed="handleExceed" :on-change="handleFileChange" :on-success="handleUploadSuccess"
                        :headers="headers" >
                        <!-- accept=".pdf,.doc,.docx,.xls,.xlsx" -->
                        <el-button slot="trigger" size="small" type="primary">选取文件</el-button>
                        <!-- <div slot="tip" class="el-upload__tip">请上传pdf、word或excel格式的文件</div> -->
                    </el-upload>
                </el-form-item>
            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button @click="addDialogVisible = false">取消</el-button>
                <el-button type="primary" @click="submitAddForm">提交</el-button>
            </div>
        </el-dialog>

        <!-- 审核报表弹窗 -->
        <el-dialog title="审核报表" :visible.sync="auditDialogVisible" width="500px">
            <el-form :model="auditForm" label-width="100px">
                <el-form-item label="状态">
                    <el-radio-group v-model="auditForm.checkstate">
                        <el-radio label="1">通过</el-radio>
                        <el-radio label="2">驳回</el-radio>
                    </el-radio-group>
                </el-form-item>
                <el-form-item label="审核内容">
                    <el-input v-model="auditForm.checkdetails" type="textarea" placeholder="请输入审核内容" :rows="4" />
                </el-form-item>
            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button @click="auditDialogVisible = false">取消</el-button>
                <el-button type="primary" @click="submitAuditForm">提交</el-button>
            </div>
        </el-dialog>
    </div>
</template>

<script>
import { getReportData, getReportInfo, addReport, editReport, auditReport } from './api/api'
import { parseTime } from '@/utils/ruoyi'
import { getToken } from "@/utils/auth"
export default {
    name: 'ReportManagement',
    dicts: ["sys_report_type"],
    data() {
        return {
            baseUrl: process.env.VUE_APP_BASE_API,
            uploadImgUrl: process.env.VUE_APP_BASE_API + '/common/upload', // 上传的图片服务器地址
            headers: {
                Authorization: "Bearer " + getToken(),
            },
            searchForm: {
                filename: ''
            },
            reportList: [],
            addForm: {
                filename: '',
                filetype: '',
                filetime: '',
                filepath: ''
            },
            auditForm: {
                checkstate: '1',
                checkdetails: ''
            },
            fileList: [],
            // 控制弹窗显示的变量
            addDialogVisible: false,
            auditDialogVisible: false,
            currentReport: null
        }
    },
    filters: {
        formatDate(time) {
            if (!time) return ''
            return parseTime(time, '{yyyy}-{mm}-{dd}')
        }
    },
    created() {
        console.log("dict.type[]", this.dict.type["sys_report_type"])
        this.query()
    },
    methods: {
        // 上传成功回调
    handleUploadSuccess(res, file) {
        console.log("上传成功", res)
      if (res.code === 200) {
        console.log("上传成功回调", res)
        // 设置文件路径
        this.addForm.filepath = res.fileName;
        // this.addForm.filename = res.originalFilename || res.data.newFileName || res.data.fileName;
        
        this.$message.success('文件上传成功')
      } else {
        this.$message.error(res.msg || '文件上传失败')
      }
    },
        async query() {
            await this.getReportData()
        },
        async getReportData() {
            let params = { ...this.searchForm }
            const res = await getReportData(params)
            if (res.code === 200) {
                this.reportList = res.rows
            }
        },
        handleSearch() {
            // 处理查询逻辑
            console.log('查询报表：', this.searchForm.reportName)
            // 实际项目中这里应该调用API获取数据
            this.getReportData()
        },
        handleAdd() {
            // 处理新增逻辑
            this.resetAddForm()
            this.addDialogVisible = true
        },
        handleEdit(row) {
            console.log('修改报表：', row)
            // 处理修改逻辑
            this.currentReport = row
            this.addForm = { ...row }
            this.addDialogVisible = true
        },
        handleAudit(row) {
            // 处理审核逻辑
            this.currentReport = row
            this.auditDialogVisible = true
        },
        async submitAddForm() {
            // 提交新增表单
            console.log('提交新增报表：', this.addForm)
            this.addForm.filetime = this.parseTime(this.addForm.filetime, '{yyyy}-{mm}-{dd}')
            let res;
            if (this.addForm.id) {
                res = await editReport(this.addForm)
            } else {
                res = await addReport(this.addForm)
            }
            if (res.code === 200) {
                this.$message.success(this.addForm.id ? '编辑成功' : '新增成功')
            } else {
                this.$message.error(this.addForm.id ? '编辑失败' : '新增失败')
            }
            this.query()
            // 实际项目中这里应该调用API提交数据
            this.addDialogVisible = false
            this.resetAddForm()
        },
        resetAddForm() {
            // 重置新增表单
            this.addForm = {
                filename: '',
                filetype: '',
                filetime: '',
                filepath: ''
            }
            this.fileList = []
        },
        handleExceed(files, fileList) {
            // 超过数量限制时的处理
            this.$message.warning('只能上传一个文件')
        },
        handleFileChange(file, fileList) {
            // 处理文件选择变化
            console.log('文件选择变化：', file, fileList)
            this.fileList = fileList.slice(-1) // 只保留最后一个文件
        },
        handleRemove(file, fileList) {
            // 处理文件删除
            console.log('删除文件：', file)
            this.addForm.filepath = ''
            this.fileList = fileList
        },
        removeFile() {
            // 处理直接删除已存在的文件
            this.addForm.filepath = ''
            this.fileList = []
        },
        async submitAuditForm() {
            // 提交审核表单
            console.log('提交审核报表：', this.auditForm, this.currentReport)
            let params = { ...this.auditForm , id : this.currentReport.id }
            let res = await auditReport(params)
            if (res.code === 200) {
                this.$message.success(res.msg || '审核成功')
            } else {
                this.$message.error(res.msg || '审核失败')
            }
            this.query();
            // 实际项目中这里应该调用API提交审核结果
            this.auditDialogVisible = false
            this.resetAuditForm()
        },
        resetAuditForm() {
            // 重置审核表单
            this.auditForm = {
                status: '通过',
                content: ''
            }
        },
        handlePreview(file) {
            // 处理文件预览
            console.log('预览文件：', file)
        }
    }
}
</script>

<style scoped>
.report-management {
    padding: 20px;
}

.search-area {
    margin-bottom: 20px;
}

.table-area {
    margin-bottom: 20px;
}

.form-area {
    display: flex;
    gap: 20px;
}

.add-form-card,
.audit-form-card {
    flex: 1;
}

.card-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
}

.el-upload {
    width: 100%;
}
</style>